import Vue from "vue";
import axios from "axios";
// Vue.use(axios);
const qs = require('qs');

import VueCookies from 'vue-cookies'
Vue.use(VueCookies)

import {
    Toast
} from 'vant';
Vue.use(Toast);


//$cookies.set('token','4c208dc8-421f-430f-af91-2f846b093c57');//lc陈绍


// axios.defaults.baseURL = process.env.BASE_URL;
axios.defaults.baseURL = '/api';
axios.defaults.timeout = 30000;
//设置默认请求头
// axios.defaults.headers.post['Content-Type'] = 'application/json; charset=utf-8';
axios.defaults.headers = {
    "Content-Type": "application/x-www-form-urlencoded",
}
var toast;
axios.interceptors.request.use(request => {
    // Toast.allowMultiple();
    // toast=Toast.loading({
    //     mask: true,
    //     message: '加载中...',
    //     duration: 0, // 持续展示 toast
    //     forbidClick: true
    // });
    if (request.data && request.headers['Content-Type'] === 'application/x-www-form-urlencoded') {
        request.data = qs.stringify(request.data); 
    }

    var token = $cookies.get('token') || localStorage.getItem('token');


    if (token && token != null) {
        request.headers["Authorization"] = 'Bearer ' + token;
    } else {
        //统一设置。全部页面需要token 
        // var returnUrl = window.location.href;
        // window.location.href = process.env.BASE_URL + "?returnUrl=" + returnUrl;
    }

    return request
}, error => {
    return Promise.reject(error);
})

axios.interceptors.response.use(response => {
    // toast.clear();
    //token过期
    console.log(response);
    if (response.data.code == 401) {
        $cookies.remove('token');
        var returnUrl = window.location.href;
        window.location.href = "http://" + window.location.host + "/login?returnUrl=" + returnUrl;
    };
    return response.data;
}, error => {
    if (response.data.code == 401) {
        $cookies.remove('token');
        var returnUrl = window.location.href;
        window.location.href = "http://" + window.location.host + "/login?returnUrl=" + returnUrl;
    };
    // toast.clear();
    if (error.response) {
        Toast.fail(error);
    }
    return Promise.reject(error);
})




export default axios;